<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例4_动态表格</title>

  <style>
    table {
      border: 1px solid;
      margin: auto;
      width: 500px;
    }

    td, th {
      text-align: center;
      border: 1px solid;
    }

    div {
      text-align: center;
      margin: 50px;
    }

  </style>
</head>
<body>

<div>
  <input type="text" id="id" placeholder="请输入编号">
  <input type="text" id="name" placeholder="请输入姓名">
  <input type="text" id="gender" placeholder="请输入性别">
  <input type="button" id="btn_add" value="添加">
</div>

<table>
  <caption>学生信息表</caption>
  <tr>
    <th>编号</th>
    <th>性别</th>
    <th>性别</th>
    <th>操作</th>
  </tr>

  <tr>
    <th>1</th>
    <th>令狐聪</th>
    <th>男</th>
    <th><a href="javascript:void(0);" onclick="deleteTr(this);">删除</a></th>
  </tr>

  <tr>
    <th>2</th>
    <th>吴天明</th>
    <th>男</th>
    <th><a href="javascript:void(0);" onclick="deleteTr(this);">删除</a></th>
  </tr>

  <tr>
    <th>3</th>
    <th>任盈盈</th>
    <th>?</th>
    <th><a href="javascript:void(0);" onclick="deleteTr(this);">删除</a></th>
  </tr>
</table>

<script>
  // 获取按钮
  document.getElementById("btn_add").onclick = function() {
    // 获取输入框内容
    var id = document.getElementById("id").value;
    var name = document.getElementById("name").value;
    var gender = document.getElementById("gender").value;

    // 创建 td，赋值 td 标签体
    // id 的 td
    var td_id = document.createElement("td");
    var text_id = document.createTextNode(id);
    td_id.appendChild(text_id);
    // name 的 td
    var td_name = document.createElement("td");
    var text_name = document.createTextNode(name);
    td_name.appendChild(text_name);
    // gender 的 td
    var td_gender = document.createElement("td");
    var text_gender = document.createTextNode(gender);
    td_gender.appendChild(text_gender);
    // a 标签的 td
    var td_a = document.createElement("td");
    var ele_a = document.createElement("a");
    ele_a.setAttribute("href", "javascript:void(0);");
    ele_a.setAttribute("onclick", "deleteTr(this);");
    var text_a = document.createTextNode("删除");
    ele_a.appendChild(text_a);
    td_a.appendChild(ele_a);

    // 创建 tr
    var tr = document.createElement("tr");
    // 添加 td 到 tr 中
    tr.appendChild(td_id);
    tr.appendChild(td_name);
    tr.appendChild(td_gender);
    tr.appendChild(td_a);

    // 获取 table
    var table = document.getElementsByTagName("table")[0];
    table.appendChild(tr);
  }

  // 删除方法
  function deleteTr(obj) {
    var table = obj.parentNode.parentNode.parentNode;
    var tr = obj.parentNode.parentNode;
    table.removeChild(tr);
  }

</script>

</body>
</html>